#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#




import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp \
	import template

class topic(db.Model):
	ttl=db.StringProperty()
	when = db.DateTimeProperty(auto_now_add=True)
	who=db.StringProperty()
	cnts=db.TextProperty()
	gd=db.IntegerProperty()
	bd=db.IntegerProperty()

class Say(db.Model):
	message=db.TextProperty(required=True)
	when=db.DateTimeProperty(auto_now_add=True)
	who=db.StringProperty()


				
class MainHandler(webapp.RequestHandler):
  def get(self):
	user = users.get_current_user()
	if user:
	      greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
	                  (user.nickname(), users.create_logout_url("/")))
	else:
	      greeting = ("<a href=\"%s\">Sign in with Google Account</a>" %
	                  users.create_login_url("/"))
	
	
	says = db.GqlQuery('SELECT * FROM Say '
	'ORDER BY when DESC')
	tpics = db.GqlQuery('SELECT * FROM topic '
	'ORDER BY when DESC')
	values = {
		'tpics':tpics,
		'user':user,
		'greeting':greeting,
		'says':says
	}
	self.response.out.write(template.render('main.html', values))
  def post(self):
	usr = users.get_current_user()
	say = Say(
		message=self.request.get(
		'message'),who=str(usr))
	say.put()
	self.redirect('/')
### User Signin
	    

def main():
  application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
